<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>get请求</button>
  <button>post请求</button>
  <script>
    var btn_get = document.querySelectorAll("button")[0]
    btn_get.addEventListener("click", function (e) {
      // 1.创建XMLHttpRequest对象
      var xhr = new XMLHttpRequest();
      console.log(xhr);
      console.log(xhr.readyState);
      // 2. 添加状态改变的回调函数,
      xhr.onreadystatechange = function () {
        console.log(xhr.readyState);
        //5 判断请求状态为4
        if (xhr.readyState == 4) {
          // 6 判断响应状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            console.log(xhr.response);
            console.log(xhr.responseText);
          }
        }
      }

      // 3. 打开连接设置请求方式和URL
      xhr.open("GET", "http://localhost:8081/student/login.php?username=admin&password=admin")


      // 4. 发送请求
      xhr.send();
    })

    var btn_post = document.querySelectorAll("button")[1]
    btn_post.addEventListener("click", function () {
      // 1 创建XMLHttpRequest对象
      var xhr = new XMLHttpRequest();

      // 2 添加请求状态改变的回调函数
      xhr.onreadystatechange = function () {
        console.log(xhr.readyState);
        console.log(xhr.statusText);
        console.log(xhr.status);

        //6 判断请求状态为4
        if (xhr.readyState == 4) {
          // 7 判断响应状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            console.log(xhr.response);
            console.log(xhr.responseText);
          }
        }
      }
      // 3 打开链接, 设置请求方式和url
      xhr.open('POST', "http://localhost:8081/student/login.php")

      // 4 设置请求内容为表单格式(窗体格式)
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      // 5 发送请求和传递数据
      xhr.send("username=admin&password=admin");

    })

  </script>
  <img src="https://ossweb-img.qq.com/upload/webplat/info/yxzj/20240426/168419543633.png" alt="">
</body>

</html>